package com.sunday.common.mq.rocket.brave.study.base.e11_PULL;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
public class PullProducerThread extends Thread {

    private DefaultMQProducer producer;

    private String topic;

    public PullProducerThread(String namesrvAddr, String producerGroup, String topic) throws MQClientException {
        this.topic = topic;
        // 实例化消息生产者Producer
        this.producer = new DefaultMQProducer(producerGroup);
        // 设置NameServer的地址
        producer.setNamesrvAddr(namesrvAddr);
        // 启动Producer实例
        producer.start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                // 创建消息，并指定Topic，Tag和消息体
                Message msg = new Message(
                        topic/* Topic */,
                        "TagA" /* Tag */,
                        ("Hello RocketMQ ").getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );
                log.info("{}", Thread.currentThread().getName());
                producer.sendOneway(msg);
                TimeUnit.SECONDS.sleep(1);
            }
            // 如果不再发送消息，关闭Producer实例。
//        producer.shutdown();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

    }


}
